//
//  RequestManager.m
//  test10010001
//
//  Created by xalo on 16/7/9.
//  Copyright © 2016年 xmaz. All rights reserved.
//

#import "QZRequestManager.h"


@interface QZRequestManager ()
@property(nonatomic,strong)FMDatabase *db;
@end

@implementation QZRequestManager

+ (instancetype)sharedManager{
    static QZRequestManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[QZRequestManager alloc] init];
    });
    return manager;
}
#pragma 属性懒加载
- (NSString *)filePath{
    if (!_filePath) {
        _filePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"myData.db"];
    }
    return _filePath;
}
- (FMDatabase *)db{
    if (!_db) {
        _db = [[FMDatabase alloc] initWithPath:self.filePath];
    }
    return _db;
}
- (void)fetchDataWithUrl:(NSString *)urlString parameters:(NSDictionary *)parameters method:(NSString *)method needToCaches:(BOOL)needCaches fetchData:(fetchData)fetchdata updateUI:(updateUI)updateui{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    if ([method isEqualToString:@"GET"]) {
        [manager GET:urlString parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            //请求成功
            fetchdata((NSData *)responseObject);
            //回主线程刷新UI
            dispatch_async(dispatch_get_main_queue(), ^{
                updateui();
            });
            //如果需要缓存
            if (needCaches) {
                //判断根据该url 是否可以取得值 有则更新 没有则插入
                NSData *data = [self selectDataWithUrl:urlString];
                if (data) {
                    [self updateData:(NSData *)responseObject url:urlString];
                }else{
                    [self insertData:(NSData *)responseObject andUrl:urlString];
                }
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            //如果需要缓存
            if (needCaches) {
                NSData *data = [self selectDataWithUrl:urlString];
                if (data) {
                    fetchdata(data);
                    dispatch_async(dispatch_get_main_queue(), ^{
                        updateui();
                    });
                }
            }
        }];
    }
    else if([method isEqualToString:@"POST"]){
        [manager POST:urlString parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            //请求成功
            fetchdata((NSData *)responseObject);
            //回主线程刷新UI
            dispatch_async(dispatch_get_main_queue(), ^{
                updateui();
            });
            //如果需要缓存
            if (needCaches) {
                //判断根据该url 是否可以取得值 有则更新 没有则插入
                NSData *data = [self selectDataWithUrl:urlString];
                if (data) {
                    [self updateData:(NSData *)responseObject url:urlString];
                }else{
                    [self insertData:(NSData *)responseObject andUrl:urlString];
                }
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            //如果需要缓存
            if (needCaches) {
                NSData *data = [self selectDataWithUrl:urlString];
                if (data) {
                    fetchdata(data);
                    dispatch_async(dispatch_get_main_queue(), ^{
                        updateui();
                    });
                }
            }
        }];
    }
}
//建表
-(BOOL)createTable{
    if ([self.db open]) {
        BOOL result = [self.db executeUpdate:@"create table if not exists cachesFile (url char primary key,data text)"];
        if (!result) {
            NSLog(@"建表失败");
            return NO;
        }
        else{
            return YES;
        }
    }
    else{
        NSLog(@"数据库打开失败");
        return NO;
    }
}
//插入数据
- (BOOL)insertData:(NSData *)data andUrl:(NSString *)url {
    if ([self createTable]) {
        NSString *dataString = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
        BOOL result = [self.db executeUpdate:[NSString stringWithFormat:@"insert into cachesFile (url , data) values ('%@','%@')",url,dataString]];
        //关闭数据库
        [self.db close];
        if (!result) {
            NSLog(@"插入失败");
            return NO;
        }
        
    }
    else{
        return NO;
    }
    return YES;
}
//查询数据
- (NSData *)selectDataWithUrl:(NSString *)url{
    if ([self.db open]) {
        FMResultSet *set = [self.db executeQuery:[NSString stringWithFormat:@"select * from cachesFile where url = '%@'",url]];
        while ([set next]) {
            NSString *dataString = [set stringForColumn:@"data"];
            NSData *data = [[NSData alloc] initWithBase64EncodedString:dataString options:NSDataBase64DecodingIgnoreUnknownCharacters];
            [self.db close];
            [set close];
            return data;
        }
        
    }else{
        NSLog(@"数据库打开失败");
        return nil;
    }
    return nil;
}

//更新数据
- (BOOL)updateData:(NSData *)data url:(NSString *)url{
    if ([self.db open]) {
        NSString *dataString = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
        BOOL result = [self.db executeUpdate:[NSString stringWithFormat:@"update cachesFile set data = '%@' where url = '%@'",dataString,url]];
        [self.db close];
        if (!result) {
            NSLog(@"更新数据失败");
            return NO;
        }else{
            return YES;
        }
    }else{
        NSLog(@"数据库打开失败");
        return NO;
    }
}

























@end
